package com.fractalist.base.core.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie操作类
 * 
 * @author radio
 * 
 */
public class CookieUtils {

	/**
	 * cookie的域名
	 */
	public static String cookieDomain = "";

	/**
	 * cookie的保存路径
	 */
	public static String cookiePath = "/";

	/**
	 * 取得cookie
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param name
	 *            cookie中的名称
	 */
	public static Cookie getCookie(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null)
			return null;
		for (int i = 0; i < cookies.length; i++) {
			if (name.equals(cookies[i].getName())) {
				return cookies[i];
			}
		}
		return null;
	}

	/**
	 * 设置cookie
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @param name
	 *            cookie中的名称
	 * @param value
	 *            cookie中的值
	 * @param maxAge
	 *            cookie的最大有效时间
	 */
	public static void setCookie(HttpServletRequest request,
			HttpServletResponse response, String name, String value, int maxAge) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(maxAge);
		if (cookieDomain != null && cookieDomain.indexOf('.') != -1) {
			cookie.setDomain('.' + cookieDomain);
		}
		cookie.setPath(cookiePath);
		response.addCookie(cookie);
	}

}
